package com.talent.web.excel;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.alibaba.excel.write.metadata.style.WriteCellStyle;
import com.alibaba.excel.write.metadata.style.WriteFont;
import com.alibaba.excel.write.style.HorizontalCellStyleStrategy;
import com.google.gson.Gson;
import com.talent.web.excel.model.DataDemo;
import com.talent.web.model.TalentResult;
import org.apache.poi.ss.usermodel.FillPatternType;
import org.apache.poi.ss.usermodel.IndexedColors;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @ClassName：ExcelController
 * @Author: hszhou
 * @Date: 2024/11/16 11:31
 * @Description: 必须描述类做什么事情, 实现什么功能
 */
@RestController
@RequestMapping("excel")
public class ExcelController {

    @Autowired
    private ExcelReadService excelReadService;

    @Autowired
    private Gson gson;

    @PostMapping("/demo")
    public TalentResult readSimple(){
        excelReadService.writeToDisk("D:\\demo.xlsx");
        return TalentResult.success();
    }

    @GetMapping("/download")
    public void download(HttpServletResponse response) throws IOException {
        try {
            response.setContentType("application/octet-stream;charset=UTF-8"); //浏览器强制下载
        //    response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            response.setCharacterEncoding("utf-8");
            String fileName = URLEncoder.encode("测试","UTF-8").replaceAll("\\+","%20");
            response.setHeader("Content-disposition","attachment,filename*=utf-8''"+fileName+".xlsx");
            excelReadService.download(response);
        }catch (Exception e){
            e.printStackTrace();
            response.reset();
            response.setContentType("application/json");
            response.setCharacterEncoding("utf-8");
            Map<String,Object> map = new HashMap<>();
            map.put("code",500);
            map.put("message",e.getMessage());
            response.getWriter().println(gson.toJson(map));
        }
    }

    //同一个sheet写入多组数据
    @GetMapping("/download2")
    public void download2(HttpServletResponse response) throws IOException {

        List data = new ArrayList<>();
        try(ExcelWriter writer =  EasyExcel.write(response.getOutputStream(), DataDemo.class).build();) {
            response.setContentType("application/octet-stream;charset=UTF-8");
            response.setCharacterEncoding("utf-8");
            String fileName = URLEncoder.encode("测试","UTF-8").replaceAll("\\+","%20");
            response.setHeader("Content-disposition","attachment,filename*=utf-8''"+fileName+".xlsx");
            WriteSheet writeSheet = EasyExcel.writerSheet("模板").build();
            for (int i = 0; i < 5; i++) {
                writer.write(data,writeSheet);
            }
        }catch (Exception e){
            e.printStackTrace();
            response.reset();
            response.setContentType("application/json");
            response.setCharacterEncoding("utf-8");
            Map<String,Object> map = new HashMap<>();
            map.put("code",500);
            map.put("message",e.getMessage());
            response.getWriter().println(gson.toJson(map));
        }
    }

    /**
     * 写入多个sheet中
     * @param response
     * @throws IOException
     */
    @GetMapping("/download3")
    public void download3(HttpServletResponse response) throws IOException {

        List<DataDemo> data = new ArrayList<>();
        try(ExcelWriter writer =  EasyExcel.write(response.getOutputStream(), DataDemo.class).build();) {
            response.setContentType("application/octet-stream;charset=UTF-8");
            response.setCharacterEncoding("utf-8");
            String fileName = URLEncoder.encode("测试","UTF-8").replaceAll("\\+","%20");
            response.setHeader("Content-disposition","attachment,filename*=utf-8''"+fileName+".xlsx");
            WriteSheet writeSheet = EasyExcel.writerSheet("模板").build();


            Map<LocalDateTime, List<DataDemo>> collect = data.stream().collect(Collectors.groupingBy(DataDemo::getBirthday));
            int index=0;
            for (LocalDateTime localDateTime : collect.keySet()) {


                WriteSheet build = EasyExcel.writerSheet(index, localDateTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd")))
                                .registerWriteHandler(horizontalCellStyleStrategy())
                                . build();
                writer.write(collect.get(localDateTime),build);
                index++;
            }


        }catch (Exception e){
            e.printStackTrace();
            response.reset();
            response.setContentType("application/json");
            response.setCharacterEncoding("utf-8");
            Map<String,Object> map = new HashMap<>();
            map.put("code",500);
            map.put("message",e.getMessage());
            response.getWriter().println(gson.toJson(map));
        }
    }


    /**
     * 设置头部样式
     * @return
     */

    public WriteCellStyle getHeader(){
        WriteCellStyle header = new WriteCellStyle();
        //设置背景颜色
        header.setFillForegroundColor(IndexedColors.RED.getIndex());
        WriteFont writeFont = new WriteFont();
        writeFont.setFontHeightInPoints((short)20);

        header.setWriteFont(writeFont);
        return header;
    }


    public WriteCellStyle getContent(){
        WriteCellStyle content = new WriteCellStyle();

        //不设置这块 下面的背景色也不起作用
        content.setFillPatternType(FillPatternType.SOLID_FOREGROUND);
        content.setFillForegroundColor(IndexedColors.GREEN.getIndex());

        WriteFont writeFont = new WriteFont();
        writeFont.setFontHeightInPoints((short)20);


        content.setWriteFont(writeFont);

        return content;
    }


    public HorizontalCellStyleStrategy horizontalCellStyleStrategy(){
        return new HorizontalCellStyleStrategy(getHeader(),getContent());
    }

}
